package com.wswy.wzcx.widget;

import android.animation.ObjectAnimator;
import android.content.Context;
import android.content.res.ColorStateList;
import android.content.res.TypedArray;
import android.support.annotation.Nullable;
import android.support.v4.content.ContextCompat;
import android.util.AttributeSet;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import com.blankj.utilcode.util.SizeUtils;
import com.wswy.wzcx.R;

public class ArrowButton extends LinearLayout implements OnClickListener{


  private static final String TAG = "ArrowButton";

  public ArrowButton(Context context) {
    this(context,null);
  }

  public ArrowButton(Context context, AttributeSet attrs) {
    this(context, attrs,0);
  }


  public ArrowButton(Context context, AttributeSet attrs, int defStyleAttr) {
    super(context, attrs, defStyleAttr);
    setOrientation(HORIZONTAL);
    setGravity(Gravity.CENTER_VERTICAL);

    TypedArray typedArray = context.obtainStyledAttributes(attrs, R.styleable.ArrowButton);
    ColorStateList colorStateList = typedArray
        .getColorStateList(R.styleable.ArrowButton_android_textColor);
    int textSize = typedArray
        .getDimensionPixelSize(R.styleable.ArrowButton_android_textSize, SizeUtils.sp2px(14));

    CharSequence text = typedArray.getText(R.styleable.ArrowButton_android_text);

    typedArray.recycle();

    textView = new TextView(context);
    if(colorStateList != null){
      textView.setTextColor(colorStateList);
    }else {
      textView.setTextColor(ContextCompat.getColorStateList(context,R.color.selected_type_text_color));
    }
    textView.setText(text);
    textView.setTextSize(TypedValue.COMPLEX_UNIT_PX,textSize);


    imgArrow = new ImageView(context);
    imgArrow.setImageResource(R.drawable.drop_down_fill);


    addView(textView,LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT);

    LayoutParams lp = new LayoutParams(LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT);
    lp.leftMargin = SizeUtils.dp2px(8);
    addView(imgArrow,lp);


    super.setOnClickListener(this);
  }


  private TextView textView;
  private ImageView imgArrow;

  private OnClickListener proxyOnClickListener;

  public void setText(CharSequence text) {
    textView.setText(text);
  }

  @Override
  public void setSelected(boolean selected) {
    super.setSelected(selected);

    if(selected){
      ObjectAnimator.ofFloat(imgArrow,View.ROTATION,0,180).start();
    }else {
      ObjectAnimator.ofFloat(imgArrow,View.ROTATION,180,360).start();
    }

  }

  @Override
  public void setOnClickListener(@Nullable OnClickListener l) {
    proxyOnClickListener = l;
  }

  @Override
  public void onClick(View v) {

    setSelected(!isSelected());

    if(proxyOnClickListener != null){
      proxyOnClickListener.onClick(v);
    }
  }
}
